package com.epfresh.supplier.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.supplier.R;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.User;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;

import com.epfresh.api.ucrop.PhotoCore;
import com.google.gson.Gson;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhaozhenqiang on 2015/10/21.
 */
public class MyInfoActivity extends BaseActivity implements PhotoCore.PhotoResult {

    /*    @ViewInject(R.id.rl)
        private RelativeLayout rl;//二维码*/
    private LinearLayout code_plate;//二维码
    private ImageView imageview;//二维码的功能还是比较麻烦的，暂时保留
    private ImageView headImage;
    private LinearLayout my_code;
    private TextView nicknameTV;
    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "avatar";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myinfo);
        headImage = (ImageView)findViewById(R.id.image_head);
        nicknameTV = (TextView)findViewById(R.id.nickname);
        View rl = findViewById(R.id.rl);
        rl.setOnClickListener(this);
        headImage.setOnClickListener(this);
        LinearLayout edit = (LinearLayout)findViewById(R.id.edit_nickname);
        edit.setOnClickListener(this);
        filePath = filePath + "_" + getUser().getAccountId();
        initview();
        ivBack.setVisibility(View.VISIBLE);

        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(200);
        photoCore.setResultWidth(200);
        updateAvatar(getUser().getAvatar());
    }

    @Override
    protected void onResume() {
        nicknameTV.setText(getUser().getNickname());
        super.onResume();
    }

    public void initview() {
        toolbarTitle.setText("我的信息");

    }

    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.image_head:
            case R.id.rl:
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)),filePath, false);
                break;
/*            case R.id.my_code:
                    *//*显示二维码，最显示的边距做了调整，有必要进一步优化显示效果,,,,该功能短期内暂停，方法实现在最下面*//*
                code_plate.setVisibility(View.VISIBLE);
                createImage();
                break;*/
            case R.id.code_plate:
                code_plate.setVisibility(View.INVISIBLE);
                break;
            case R.id.edit_nickname:
                Intent edit = new Intent(this, EditNicknameActivity.class);

                startActivity(edit);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void mPicUp(String id) {
        String keys[] = {"id", "avatarImgId"};
        String values[] = {getUser().getAccountId(), id};

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();

        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_updateAvatar);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        //data.setToken(getUser().getToken());
        Map<String, String> map = new HashMap<>();
        map.put("id", getUser().getAccountId());
        map.put("avatarImgId", id);
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_updateAvatar, onRequestListenerUp);
    }

    OnRequestListener<StatusEntity> onRequestListenerUp = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                getUser().delDeliveryAddressCount();
                toast(BaseApplication.getDoc().getBeenSubmitted());
            }
            updateUserProfile();
        }
    };



    /*显示二维码，最显示的边距做了调整，有必要进一步优化显示效果,,,,该功能短期内暂停*/
/*    private void createImage() {
        try {
            // 需要引入core包
            QRCodeWriter writer = new QRCodeWriter();
            String text = "测试二维码显示";
            if (text == null || "".equals(text) || text.length() < 1) {
                return;
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, 480, 480, hints);
            int[] pixels = new int[480 * 480];

            boolean isFirstBlackPoint = false;
            int startX = 0;
            int startY = 0;

            for (int y = 0; y < 480; y++) {
                for (int x = 0; x < 480; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * 480 + x] = 0xff000000;
                    } else {
                        pixels[y * 480 + x] = 0xffffffff;
                    }

                }
            }
            Bitmap bitmap = Bitmap.createBitmap(480, 480,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, 480, 0, 0, 480, 480);
            Bitmap bitmapTest = bitmap.createBitmap(bitmap, 25, 25, 430, 430);//按默认返回的图像调整页面边距
            imageview.setImageBitmap(bitmapTest);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }*/

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            User user = response.getResponseElement();
            user.setAccess_token(getUser().getAccess_token());
            user.setAccountId(getUser().getAccountId());
            user.setPassword(getUser().getPassword());
            user.setTag(UUID.randomUUID().toString());
            user.setAccess_token(ApplicationHelper.getInstance().getUser().getAccess_token());
            updateUser(user);

            nicknameTV.setText(user.getNickname());
            updateAvatar(user.getAvatar());
        }
    };


    public void updateUserProfile() {

        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("flag", "main");
            startActivity(intent);

        } else {
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_profile);
            //data.setToken(getUser().getToken());

            data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("accountId", getUser().getAccountId());

            data.setParameters(map);
            request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_account_profile, onRequestListener);
        }
    }


    RequestTag tag = new RequestTag();

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            RequestTag requestTag = (RequestTag) tag;

            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }

            mPicUp(id + "");

        }
    };

    public void uploadImage(String filePath, int id) {

        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_file_upload);
            //data.setToken(getUser().getToken());

            data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);

            data.setParameters(map);


            tag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_file_upload;
            tag.action = id;
            request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateAvatar(String url) {
        String urlHead = null;
//        if (url != null) {
//            String[] split = url.split("-AVATAR?");
//            if (split != null && split.length > 1) {
//                urlHead = split[0];
//            }
//        }
        if (urlHead == null) {
            urlHead = url;
        }
        ImageLoader.getInstance().displayImage(urlHead, new ImageViewAware(headImage), BaseApplication.getAvatarOptions(url), null, null, null);
    }

    @Override
    public void onSuccess(String path) {
//        updateAvatar(path);
        uploadImage(filePath, 0);
    }

    @Override
    public void onFail(String msg) {

    }

    @Override
    public void onReupload() {

    }

    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(tag);
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
